package com.xysd.express.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.xysd.express.R;
import com.xysd.express.activity.CompanyDetailsActivity;
import com.xysd.express.adapter.CompanyListAdpter;
import com.xysd.express.base.BaseFragment;
import com.xysd.express.bean.CompanyListObj;
import com.xysd.express.bean.User;
import com.xysd.express.util.JSONParser;
import com.xysd.express.util.ToastUtil;
import com.xysd.express.util.http.HttpCallBack;
import com.xysd.express.util.http.HttpUtil;
import com.xysd.express.widget.BaseSwipeRefreshLayout;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

/**
 * 企业
 */
@ContentView(R.layout.fragment_company)
public class CompanyFragment extends BaseFragment {
    @ViewInject(R.id.company_rv)
    private RecyclerView company_rv;
    @ViewInject(R.id.swiperefreshlayout)
    private BaseSwipeRefreshLayout swiperefreshlayout;

    CompanyListAdpter adapter;
    List<CompanyListObj.Company> dataList;
    List<CompanyListObj.Company> allDataList = new ArrayList<>();
    int page = 1;
    int pageSize = 10;
    int totleSize;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return x.view().inject(this, inflater, container);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        init();
    }


    //重写fragment是否对用户可视，当可视时加载数据（解决viewpager的预加载问题）
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isCanLoadData();
    }

    private void isCanLoadData() {
        if (getUserVisibleHint()) {
            if (User.getInstance().isLogin)
                getData();
        }
    }

    private void init() {
        dataList = new ArrayList<>();
        adapter = new CompanyListAdpter(R.layout.item_company, mActivity);
        company_rv.setLayoutManager(new LinearLayoutManager(mActivity));
        company_rv.setAdapter(adapter);
        adapter.openLoadAnimation();
        adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                page++;
                getData();
            }
        }, company_rv);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Log.i("onItemClick", "position:" + position + ";totle:" + adapter.getItemCount() + ";");
                Intent intent = new Intent(mActivity, CompanyDetailsActivity.class);
                intent.putExtra("id", allDataList.get(position).CommpanyId);
                startActivity(intent);
            }
        });
        initRefresh();
    }

    private void initRefresh() {
        setSwipeRefreshLayout(swiperefreshlayout);
        setOnRefreshListener(new BaseSwipeRefreshLayout.OnRefresh() {
            @Override
            public void refresh() {
                page = 1;
                allDataList.clear();
                getData();
            }
        });
    }

    private void getData() {
        HttpUtil.getCompanyList(page, pageSize, new HttpCallBack() {
            @Override
            public void onSuccess(String result) {
                Log.i("企业列表", result);
                String code = JSONParser.getStringFromJsonString("Status", result);
                String msg = JSONParser.getStringFromJsonString("Msg", result);
                if ("0".equals(code)) {
                    dataList = new Gson().fromJson(result, CompanyListObj.class).Data;
                    totleSize = new Gson().fromJson(result, CompanyListObj.class).Total;
                    if (null == dataList || dataList.size() == 0) {
                        adapter.loadMoreEnd();
                        return;
                    }
                    if (page == 1) {
                        adapter.setNewData(dataList);
                        allDataList = dataList;
                    } else {
                        adapter.addData(dataList);
                        allDataList.addAll(dataList);//加载下一页数据之后添加到总数据里面，以供adapter的onItemClickListener使用
                    }
                    //判断是否已经获取完所有数据
                    if (dataList.size() < pageSize) {
                        adapter.loadMoreEnd();
                    } else {
                        if (page * pageSize == totleSize) {
                            adapter.loadMoreEnd();
                        } else {
                            adapter.loadMoreComplete();
                        }
                    }
                } else {
                    ToastUtil.show(msg);
                }
            }

            @Override
            public void onFailure(String error) {
                Log.e("企业列表", error);
            }
        });
    }
}
